/*
 *  Copyright 2012 Dirk Vranckaert
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package eu.vranckaert.vvl.activities.preferences.alarm;

import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import eu.vranckaert.vvl.R;
import eu.vranckaert.vvl.activities.list.adapter.TrafficInfoAlarmsAdapter;
import eu.vranckaert.vvl.model.TrafficInfoAlarm;
import eu.vranckaert.vvl.utils.context.Constants;
import eu.vranckaert.vvl.utils.context.Logger;
import eu.vranckaert.vvl.utils.context.Preference;

import java.util.Collections;
import java.util.List;

/**
 * User: DIRK VRANCKAERT
 * Date: 28/02/12
 * Time: 8:23
 */
public class AlarmsActivity extends ListActivity {
    private static final String LOG_TAG = AlarmsActivity.class.getSimpleName();

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarms);

        registerForContextMenu(getListView());
    }
    
    public void onAddAlarmClick(View view) {
        Intent intent = new Intent(AlarmsActivity.this, AlarmChooserActivity.class);
        startActivity(intent);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        if (v.getId() == android.R.id.list) {
            super.onCreateContextMenu(menu, v, menuInfo);
            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
            TrafficInfoAlarm item = ((TrafficInfoAlarmsAdapter) getListView().getAdapter()).getItem(info.position);

            menu.setHeaderTitle(R.string.preferences_category_alarms_list_context_menu_title);

            menu.add(Menu.NONE,
                    Constants.ContentMenuItems.DELETE,
                    Menu.NONE,
                    R.string.preferences_category_alarms_list_context_menu_option_delete
            );
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        TrafficInfoAlarm alarm = ((TrafficInfoAlarmsAdapter) getListView().getAdapter()).getItem(info.position);

        if (item.getItemId() == Constants.ContentMenuItems.DELETE) {
            AlarmManager am = (AlarmManager)AlarmsActivity.this.getSystemService(Context.ALARM_SERVICE);
            List<PendingIntent> pendingIntents = alarm.getPendingIntents(AlarmsActivity.this);
            for (PendingIntent pendingIntent : pendingIntents) {
                am.cancel(pendingIntent);
            }

            Preference.deleteAlarm(AlarmsActivity.this, alarm);
            new AlarmLoader().execute();
        }

        return true;
    }
    
    private class AlarmLoader extends AsyncTask<Void, Void, List<TrafficInfoAlarm>> {

        @Override
        protected List<TrafficInfoAlarm> doInBackground(Void... voids) {
            List<TrafficInfoAlarm> alarms = Preference.getAlarms(AlarmsActivity.this);
            Collections.sort(alarms);
            if (Logger.isLogEnabled())
                Log.d(LOG_TAG, "Number of alarms found: " + alarms.size());

            return alarms;
        }

        @Override
        protected void onPostExecute(List<TrafficInfoAlarm> alarms) {
            if (alarms != null && alarms.size() > 0) {
                if (getListView().getAdapter() == null) {
                    TrafficInfoAlarmsAdapter adapter = new TrafficInfoAlarmsAdapter(
                            AlarmsActivity.this, alarms, R.layout.list_item_alarm);
                    setListAdapter(adapter);
                } else {
                    ((TrafficInfoAlarmsAdapter) getListView().getAdapter()).refill(alarms);
                }

                getListView().setVisibility(View.VISIBLE);
            } else {
                getListView().setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        new AlarmLoader().execute();
    }
}